import lldb
from panda.debugger import TypeRegistrator

from ..common import (
    SummaryRecognizer,
    c_substr,
    dereference_value,
    error_ctx,
)


class StringView(SummaryRecognizer):
    TYPE_NAME = 'std::string_view'

    @staticmethod
    def is_type(sbtype: lldb.SBType, internal_dict: dict):
        with error_ctx():
            return sbtype.GetName() == StringView.TYPE_NAME

    @staticmethod
    def summary(valobj: lldb.SBValue, internal_dict: dict):
        with error_ctx():
            value = dereference_value(valobj)
            len = int(value.EvaluateExpression('_M_len').GetValueAsUnsigned())
            chars = str(value.EvaluateExpression('_M_str').GetSummary())
            return c_substr(chars, len)


def register(r: TypeRegistrator):
    r.add_type(
        StringView,
    )
    r.add_summary(
        type_name=r'^std::pair<.+>',
        expr='\\{ first=\\{${var.first}\\}; second=\\{${var.second}\\} \\}',
        novalue=True,
        regex=True,
    )
    r.add_summary(
        type_name='^std::vector<',
        expr='size=${var%#}',
        novalue=True,
        regex=True,
    )
